import { useCookieStore } from "@/stores";
// base URL
const baseUrl = "https://service-d9pwt01b-1304986681.bj.apigw.tencentcs.com/";

// 请求拦截器
uni.addInterceptor("request", {
  // 拦截前触发
  invoke(options) {
    const cookieStore = useCookieStore();
    if (!options.url.startsWith("http")) {
      options.url = baseUrl + options.url;
    }
    if (cookieStore.cookie.cookie) {
      options.data.cookie = cookieStore.cookie.cookie;
    }
  },
});

// 请求接口 promise 化
const request = (options) => {
  return new Promise((reslove, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          reslove(res.data);
        } else {
          console.log(res);
          reject(res);
          uni.showToast({
            icon: "error",
            title: "请求错误",
          });
        }
      },
      fail: (err) => {
        console.log(err);
        uni.showToast({
          icon: "error",
          title: "网络错误",
        });
      },
    });
  });
};

export default request;
